import { useState, useCallback } from 'react';
import { ModelInfo, PredictionResult } from '../types';
import { Button, Panel, FileUploader, ModelSelector } from './shared';
import { PlayIcon, TrashIcon } from './icons';
import { predict } from '../services/backendApi';

const MOCK_MODELS: ModelInfo[] = [
    { id: 'resnext50_20240729_1030.pth', name: 'resnext50_20240729_1030.pth', createdAt: '2024-07-29' },
    { id: 'resnext50_20240728_1800.pth', name: 'resnext50_20240728_1800.pth', createdAt: '2024-07-28' },
];

const MOCK_PREDICTIONS: PredictionResult[] = [
    { label: 'wg01', probability: 0.9234 },
    { label: 'wg02', probability: 0.0512 },
    { label: 'wg03', probability: 0.0156 },
];

interface UserTestViewProps {
  isGpuBusy: boolean;
  setIsGpuBusy: (isBusy: boolean) => void;
  setStatusMessage: (message: string) => void;
}

const UserTestView = ({ isGpuBusy, setIsGpuBusy, setStatusMessage }: UserTestViewProps) => {
  const [isRecognizing, setIsRecognizing] = useState(false);
  const [imageSrc, setImageSrc] = useState<string | null>(null);
  const [selectedModel, setSelectedModel] = useState<string | null>(null);
  const [predictions, setPredictions] = useState<PredictionResult[] | null>(null);
  
  const clearState = useCallback(() => {
    setIsRecognizing(false);
    setImageSrc(null);
    setSelectedModel(MOCK_MODELS[0]?.id || null);
    setPredictions(null);
    setStatusMessage('状态: 空闲');
  }, [setStatusMessage]);

const handleRecognize = async () => {
  if (!imageSrc || !selectedModel) {
    setStatusMessage('错误: 请选择模型并上传图片');
    return;
  }
  setIsRecognizing(true);
  setPredictions(null);
  setStatusMessage('正在调用模型进行推理...');

  try {
    // 将 base64 图片转为 File 对象
    const res = await fetch(imageSrc);
    const blob = await res.blob();
    const file = new File([blob], 'uploaded.png', { type: blob.type });

    // 调用后端接口
    const result = await predict(file, selectedModel);
    if (result.success && result.predictions) {
      setPredictions(result.predictions);
      setStatusMessage('识别完成！');
    } else {
      setStatusMessage('推理失败，请检查模型和图片格式');
    }
  } catch (error) {
    setStatusMessage('推理请求失败，请稍后重试');
  } finally {
    setIsRecognizing(false);
  }
};


  const handleFileUpload = (file: File) => {
    const reader = new FileReader();
    reader.onload = (e) => {
      setImageSrc(e.target?.result as string);
      setPredictions(null);
    };
    reader.readAsDataURL(file);
    setStatusMessage(`图片已上传: ${file.name}`);
  };

  return (
    <div className="p-4 flex flex-col gap-4 h-full hacker-scrollbar overflow-y-auto">
      <Panel title="单图识别">
        <div className="flex flex-wrap gap-4 items-end">
            <ModelSelector selectedModel={selectedModel} onSelectModel={setSelectedModel} disabled={isRecognizing || isGpuBusy} />
            <div className="flex flex-col gap-2">
                <label className="text-sm text-green-300">上传图片</label>
                <FileUploader onFileUpload={handleFileUpload} buttonText="选择图片文件" disabled={isRecognizing || isGpuBusy} />
            </div>
            <div className="flex-grow" />
            <Button onClick={handleRecognize} disabled={isRecognizing || isGpuBusy || !imageSrc || !selectedModel} icon={<PlayIcon className="w-4 h-4" />}>开始识别</Button>
            <Button onClick={clearState} disabled={isRecognizing || isGpuBusy} icon={<TrashIcon className="w-4 h-4" />}>清空</Button>
        </div>
      </Panel>
      
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4 flex-grow">
        <Panel title="上传图片预览">
            <div className="flex items-center justify-center h-full bg-black/30 border-2 border-dashed border-green-800">
                {imageSrc ? (
                    <img src={imageSrc} alt="上传的图片" className="max-h-full max-w-full object-contain" />
                ) : (
                    <div className="text-gray-500">等待图片上传...</div>
                )}
            </div>
        </Panel>
        <Panel title="识别结果">
            <div className="flex flex-col justify-center h-full space-y-4">
                {predictions ? (
                    predictions.map((p, index) => (
                        <div key={index} className={`p-4 border rounded-md ${index === 0 ? 'border-cyan-400 bg-cyan-900/40' : 'border-green-700 bg-green-900/20'}`}>
                            <div className="flex justify-between items-center">
                                <span className={`text-2xl font-bold ${index === 0 ? 'text-cyan-300 glow-cyan' : 'text-green-300'}`}>{p.label}</span>
                                <span className={`font-mono text-lg ${index === 0 ? 'text-cyan-200' : 'text-green-200'}`}>{ (p.probability * 100).toFixed(2) }%</span>
                            </div>
                            <div className="w-full bg-gray-700 rounded-full h-2.5 mt-2">
                                <div className={`${index === 0 ? 'bg-cyan-400' : 'bg-green-500'}`} style={{ width: `${p.probability * 100}%`, height: '100%', borderRadius: 'inherit' }}></div>
                            </div>
                            <div className="text-xs text-right mt-1 text-gray-400">{index === 0 ? '最高置信度' : `备选结果 ${index}`}</div>
                        </div>
                    ))
                ) : (
                    <div className="text-gray-500 text-center">等待识别...</div>
                )}
            </div>
        </Panel>
      </div>
    </div>
  );
};

export default UserTestView;
